import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { createTRPCRouter, protectedProcedure } from "../trpc";

const stepSchema = z.object({
  title: z.string().min(1, "步骤标题不能为空"),
  description: z.string().optional(),
  taskId: z.string(),
});

export const stepsRouter = createTRPCRouter({
  create: protectedProcedure
    .input(stepSchema)
    .mutation(async ({ ctx, input }) => {
      // 获取当前最大的 orderIndex
      const maxOrderStep = await ctx.db.step.findFirst({
        where: { taskId: input.taskId },
        orderBy: { orderIndex: 'desc' },
      });

      const newOrderIndex = (maxOrderStep?.orderIndex ?? -1) + 1;

      return ctx.db.step.create({
        data: {
          ...input,
          orderIndex: newOrderIndex,
          status: "NOT_STARTED",
        },
      });
    }),

  delete: protectedProcedure
    .input(z.string())
    .mutation(async ({ ctx, input: stepId }) => {
      return ctx.db.step.delete({
        where: { id: stepId },
      });
    }),

  updateStatus: protectedProcedure
    .input(z.object({
      stepId: z.string(),
      status: z.enum(["NOT_STARTED", "IN_PROGRESS", "COMPLETED"]),
    }))
    .mutation(async ({ ctx, input }) => {
      const step = await ctx.db.step.findUnique({
        where: { id: input.stepId },
        include: {
          task: true,
          completions: {
            where: { userId: ctx.session.user.id }
          }
        },
      });

      if (!step) {
        throw new TRPCError({
          code: "NOT_FOUND",
          message: "步骤不存在",
        });
      }

      // 更新步骤状态
      const updatedStep = await ctx.db.step.update({
        where: { id: input.stepId },
        data: { status: input.status },
      });

      // 如果标记为完成，创建完成记录（如果不存在）
      if (input.status === "COMPLETED") {
        if (step.completions.length === 0) {
          await ctx.db.stepCompletion.create({
            data: {
              stepId: input.stepId,
              userId: ctx.session.user.id,
            },
          });
        }
      } else {
        // 如果标记为未完成，删除完成记录（如果存在）
        if (step.completions.length > 0) {
          await ctx.db.stepCompletion.deleteMany({
            where: {
              stepId: input.stepId,
              userId: ctx.session.user.id,
            },
          });
        }
      }

      // 计算任务进度
      const allStepsInTask = await ctx.db.step.findMany({
        where: { taskId: step.taskId },
        include: {
          completions: {
            where: { userId: ctx.session.user.id }
          }
        }
      });
      
      const totalSteps = allStepsInTask.length;
      const completedSteps = allStepsInTask.filter(s => 
        s.completions.length > 0
      ).length;
      
      // 如果所有步骤都完成，更新任务状态
      if (completedSteps === totalSteps && totalSteps > 0) {
        await ctx.db.task.update({
          where: { id: step.taskId },
          data: { status: "COMPLETED" }
        });
      } else if (completedSteps > 0) {
        await ctx.db.task.update({
          where: { id: step.taskId },
          data: { status: "IN_PROGRESS" }
        });
      } else {
        await ctx.db.task.update({
          where: { id: step.taskId },
          data: { status: "NOT_STARTED" }
        });
      }

      // 更新课程进度
      await ctx.db.$transaction(async (prisma) => {
        const enrollment = await prisma.enrollment.findFirst({
          where: {
            courseId: step.task.courseId,
            studentId: ctx.session.user.id
          }
        });

        if (enrollment) {
          // 获取课程中所有步骤
          const allCourseSteps = await prisma.step.findMany({
            where: {
              task: {
                courseId: step.task.courseId
              }
            },
            include: {
              completions: {
                where: { userId: ctx.session.user.id }
              }
            }
          });

          const totalCourseSteps = allCourseSteps.length;
          const completedCourseSteps = allCourseSteps.filter(s => 
            s.completions.length > 0
          ).length;

          // 计算进度百分比
          const progress = totalCourseSteps > 0 
            ? Math.round((completedCourseSteps / totalCourseSteps) * 100) 
            : 0;

          // 更新注册记录的进度
          await prisma.enrollment.update({
            where: { id: enrollment.id },
            data: { 
              progress,
              status: progress === 100 ? "COMPLETED" : "ENROLLED"
            }
          });
        }
      });

      return updatedStep;
    }),
  getProgress: protectedProcedure
    .input(z.object({
      taskId: z.string(),
    }))
    .query(async ({ ctx, input }) => {
      const steps = await ctx.db.step.findMany({
        where: { taskId: input.taskId },
        include: {
          completions: {
            where: { userId: ctx.session.user.id },
          },
        },
      });

      const total = steps.length;
      const completed = steps.filter(step => 
        step.status === "COMPLETED" || step.completions.length > 0
      ).length;

      return {
        total,
        completed,
        percentage: total > 0 ? Math.round((completed / total) * 100) : 0,
      };
    }),
  reorder: protectedProcedure
    .input(z.object({
      taskId: z.string(),
      updates: z.array(z.object({
        id: z.string(),
        orderIndex: z.number(),
      })),
    }))
    .mutation(async ({ ctx, input }) => {
      const { taskId, updates } = input;

      // 验证任务存在且用户有权限
      const task = await ctx.db.task.findUnique({
        where: { id: taskId },
        include: { steps: true },
      });

      if (!task) {
        throw new TRPCError({
          code: "NOT_FOUND",
          message: "任务不存在",
        });
      }

      // 批量更新步骤顺序
      await ctx.db.$transaction(
        updates.map(({ id, orderIndex }) =>
          ctx.db.step.update({
            where: { id },
            data: { orderIndex },
          })
        )
      );

      return true;
    }),
  update: protectedProcedure
    .input(z.object({
      stepId: z.string(),
      title: z.string().min(1, "步骤标题不能为空"),
      description: z.string().optional(),
    }))
    .mutation(async ({ ctx, input }) => {
      const { stepId, ...data } = input;

      // 修改查询以包含完整的任务信息
      const step = await ctx.db.step.findUnique({
        where: { id: stepId },
        include: {
          task: {
            include: {
              course: true, // 包含课程信息以获取创建者
            },
          },
        },
      });

      if (!step) {
        throw new TRPCError({
          code: "NOT_FOUND",
          message: "步骤不存在",
        });
      }

      // 验证权限：课程创建者或管理员可以修改
      if (
        step.task.course.teacherId !== ctx.session.user.id && 
        ctx.session.user.role !== "ADMIN"
      ) {
        throw new TRPCError({
          code: "FORBIDDEN",
          message: "没有权限修改此步骤",
        });
      }

      return ctx.db.step.update({
        where: { id: stepId },
        data,
      });
    }),
  getById: protectedProcedure
    .input(z.object({
      stepId: z.string(),
    }))
    .query(async ({ ctx, input }) => {
      const step = await ctx.db.step.findUnique({
        where: { id: input.stepId },
        include: {
          task: {
            select: {
              id: true,
              courseId: true,
              title: true,
            },
          },
        },
      });

      if (!step) {
        throw new TRPCError({
          code: "NOT_FOUND",
          message: "步骤不存在",
        });
      }

      return step;
    }),
}); 